<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 订单管理
 * @filename admin_order.php
 * @author hmw
 *
 */
class Admin_order extends MY_Controller {

	function Admin_order()
	{
		parent::MY_Controller();
		parent::check_admin_login();
	}

	/**
	 * 订单列表
	 * @param $offset
	 * @return unknown_type
	 */
	function order_admin($offset=0){
		$this->load->model('Morders');

		$this->config->load('setup');
		$states = $this->config->item('order_state');

		$total = $this->Morders->get_order_count();

		$this->load->library('pagination');

		$config['base_url'] = base_url().'admin_order/order_admin/';
		$config['total_rows'] = $total;
		$config['per_page'] = 10;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['first_link'] = '第一页';
		$config['last_link'] = '最后页';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

		$temps = $this->Morders->get_orders($offset,$config['per_page']);

        $orders = array();
        if($temps){
        	$this->load->helper('common');
            foreach($temps as $arr){
                $orders[] = get_order_info($arr['order_id']);
            }
        }

        //echo $total;exit;

		$this->template->view('admin/order_admin',array('orders'=>$orders,'page_html'=>$page_html,'states'=>$states));
	}

	/**
	 * 修改订单
	 * @param $order_id
	 * @return null
	 */
	function order_edit($order_id){
		$this->load->helper('common');
		$order = get_order_info($order_id);
		$this->config->load('setup');
		$states = $this->config->item('order_state');
		$dai_states = $this->config->item('dai_state');
		//print_r($states);exit;
		$this->template->view('admin/order_edit',array('order'=>$order,'states'=>$states,'dai_states'=>$dai_states));
	}

	/**
	 * 处理修改订单
	 * @return unknown_type
	 */
	function order_modify(){
		$order_id = $this->input->post('order_id');
		$this->load->helper('common');
		$info = get_order_info($order_id);
		$form = array('uid','real_price','pay_count','order_state','tel','qq','dai_state');
		$data = $this->input->get_data($form);
		if($info['order_state'] >= 2 && $data['order_state'] == 1){
			echo '付款后，不可再将订单状态改为已下单，要么将此订单作废！<br />';
			echo '<a href="javascript:window.history.back();">返回</a>';
		}
        if($data['order_state'] == 2){
            $data['pay_count'] = $info['real_price'];
        }
		$this->load->model('Morders');
		$this->load->helper('common');
		if($this->Morders->update_order_data($order_id,$data)){
			$this->load->helper('common');
			$new = get_order_info($order_id);
			self::_process_order($info,$new);
			log_common('admin','admin_order.php','order_modify','order edit succ, orderid:'.$order_id,$data);
			echo '订单信息修改成功！<br />';
			echo '<a href="/admin_order/order_admin/">返回列表</a> | <a href="/admin_order/order_view/'.$order_id.'/">查看详情</a>';
		} else {
			log_common('admin','admin_order.php','order_modify','order edit fail, orderid:'.$order_id,$data);
			echo '订单信息修改失败！<br />';
			echo '<a href="javascript:window.history.back();">返回</a>';
		}
	}

    /**
     * 删除订单
     * @param <type> $order_id
     */
    function order_del($order_id){
        if(!$order_id){
            echo '订单不存在';exit;
        }
        $data = array('order_state'=>'-1');
        $this->load->model('Morders');
		if($this->Morders->update_order_data($order_id,$data)){
			log_common('admin','admin_order.php','order_del','order del succ, orderid:'.$order_id,$data);
			echo '成功删除订单！<br />';
			echo '<a href="/admin_order/order_admin/">返回列表</a>';
		} else {
			log_common('admin','admin_order.php','order_del','order del fail, orderid:'.$order_id,$data);
			echo '订单删除失败！';
			echo '<a href="javascript:window.history.back();">返回</a>';
		}
    }

    function order_send($order_id){
    	if(!$order_id){
            echo '订单不存在';exit;
        }
        $this->load->helper('common');
        $info = get_order_info($order_id);
        $this->template->view('admin/order_send',array('order_id'=>$order_id,'info'=>$info));
    }

    function send_order(){
    	$order_id = $this->input->post('order_id');
    	$dai = $this->input->post('dai');
    	if(!$dai){
    		echo '必须填写代打人代码<br />';
    		echo '<a href="javascript:window.history.back();">返回</a>';
    		exit();
    	} elseif (strtoupper(substr($dai,0,2)) != 'WB'){
    		echo '请填写正确的代打人代码，以WB开头！<br />';
    		echo '<a href="javascript:window.history.back();">返回</a>';
    		exit();
    	}
    	$this->load->model('Morders');
    	if(!$this->Morders->check_orderid_exist($order_id)){
    		echo '你所选择的订单已经不存在！<br />';
    		echo '<a href="javascript:window.history.back();">返回</a>';
    		exit();
    	}
    	$ol = $this->Morders->get_order_dai($order_id);
    	if($ol){
    		echo '此订单已经发送给！'.$ol.'，你确定将订单再次发送给：'.$dai.'吗？<br />';
    		parent::set_session_value('send_order',array('orderid'=>$order_id,'dai'=>$dai,'ol'=>$ol));
    		echo '<input type="button" value="确定发送" onclick="window.location.href=\'/admin_order/send_confirm\'" />&nbsp;<input type="button" value="取消" onclick="window.history.back();" />';
    		exit();
    	}
    	$this->load->model('Mmember');
    	if(!$this->Mmember->check_user_exist($dai)){
    		echo '你所输入的推广代码：'.$dai.'不存在！<br />';
    		echo '<a href="javascript:window.history.back();">返回</a>';
    		exit();
    	}
    	if($this->Morders->update_order_data($order_id,array('dai'=>$dai))){
            //此处做一个代打人员提成计算的功能
            self::_process_dai_discount($order_id,$dai);
            self::_update_important($order_id,$dai);
            echo '订单发送成功，成功发送给：'.$dai.'<br />';
    		echo '<a href="/admin_order/order_admin/">返回列表</a>';
    	}
    }
    
    function send_confirm(){
    	$info = parent::get_session_value('send_order');
    	$order_id = $info['orderid'];
    	$dai = $info['dai'];
    	$ol = $info['ol'];
    	$this->load->model('Mmember');
    	$this->load->model('Morders');
    	if(!$this->Mmember->check_user_exist($dai)){
    		echo '你所输入的推广代码：'.$dai.'不存在！<br />';
    		echo '<a href="javascript:window.history.back();">返回</a>';
    		exit();
    	}
    	$this->load->model('Mdiscount');
    	if($this->Mdiscount->delete_discount($order_id,$ol)){
	    	if($this->Morders->update_order_data($order_id,array('dai'=>$dai))){
	            //此处做一个代打人员提成计算的功能
	            self::_process_dai_discount($order_id,$dai);
	            echo '订单发送成功，成功发送给：'.$dai.'<br />';
	    		echo '<a href="/admin_order/order_admin/">返回列表</a>';
	    		return true;
	    	}
    	} else {
    		echo '订单删除失败！';
    		return false;
    	}
    }

    function _process_dai_discount($orderid,$dai){
        $this->load->model('Morders');
        $info = $this->Morders->get_order_info($orderid);
        if($info['uid'] && $info['uid'] == $dai){
            echo '推广员和代打人员是同一个人，无须再次计算提成。<br />';
        } else {
            $this->load->model('Mproduct');
            $pinfo = $this->Mproduct->get_product_info($info['product']);
            $this->load->helper('common');
            $discount = get_discount($dai,$orderid);
            $data = array('order_id'=>$orderid,'username'=>$dai,'price'=>$info['price'],'discount'=>$discount,'add_time'=>date('Y-m-d H:i:s'));
            $this->load->model('Mdiscount');
            if($this->Mdiscount->new_discount($data)){
                $this->load->model('Mmember');
                $uinfo = $this->Mmember->get_user_info('username',$dai);
                $uinfo['order_count']++;
                $this->Mmember->update_member_data($dai,array('order_count'=>$uinfo['order_count']));
                echo '代打人员：'.$dai.'，提成：'.$discount.'成功插入！<br />';
            } else {
                echo '代打提成插入失败！<br />';
            }
        }
    }
    
    function _update_important($orderid,$dai){
    	$this->load->model('Mimportant');
    	$values = array('orderid'=>$orderid,'wb_dai'=>$dai);
    	return $this->Mimportant->save_important($values);
    }

    function order_view($order_id){
        if(!$order_id){
            echo '订单不存在';exit;
        }
        $this->load->helper('common');
        $order = get_order_info($order_id);
        $this->template->view('admin/order_view',array('order'=>$order));
    }

	function order_search(){
		$this->template->view('admin/order_search');
	}

	/**
	 * 显示订单搜索结果
	 * @param $offset
	 * @return unknown_type
	 */
	function search_result($offset=0){
		//接收搜索参数
		$session_state 	= parent::get_session_value('order_state');
		$session_word 	= parent::get_session_value('order_word');
		$session_start 	= parent::get_session_value('order_start');
		$session_end 	= parent::get_session_value('order_end');
		$order_state	= $this->input->post('order_state');
		$word			= $this->input->post('word');
		$start			= $this->input->post('start');
		$end			= $this->input->post('end');
		$order_state 	= $order_state !== FALSE ? $order_state : $session_state;
		$word	 		= $word !== FALSE ? $word : $session_word;
		$word = $word == '请输入关键字' ? '' : $word;
		$start	 		= $start ? $start : $session_start;
		$end	 		= $end ? $end : $session_end;
		if(!$start || $start == '0000-00-00'){
			$start = '2008-01-01 00:00:00';
		} elseif(strlen($start) == 10) {
			$start = $start.' 00:00:00';
		}
		if(!$end){
			$end = date('Y-m-d H:i:s');
		} elseif(strlen($end) == 10) {
			$end = $end.' 23:59:59';
		}
		parent::set_session_value('order_state',$order_state);
		parent::set_session_value('order_word',$word);
		parent::set_session_value('order_start',$start);
		parent::set_session_value('order_end',$end);
		//echo $order_state.'|'.$word.'|'.$start.'|'.$end;
		//echo $order_state.'|'.$word;exit;
		$this->config->load('setup');
		$states = $this->config->item('order_state');

		$this->load->model('Morders');
		$total = $this->Morders->get_search_count($order_state,$word,$start,$end);
		//echo $total;exit;
		$this->load->library('pagination');

		$config['base_url'] = base_url().'admin_order/search_result/';
		$config['total_rows'] = $total;
		$config['per_page'] = 10;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['first_link'] = '第一页';
		$config['last_link'] = '最后页';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

		$temps = $this->Morders->get_search_orders($order_state,$word,$offset,$config['per_page'],$start,$end);
		$orders = array();
		$this->load->helper('common');
        if($temps){
            foreach($temps as $arr){
                $orders[] = get_order_info($arr['order_id']);
            }
        }
		//echo '@@@'.$total.'@@@'.count($orders);
		$this->template->view('admin/order_admin',array('orders'=>$orders,'page_html'=>$page_html,'states'=>$states,'order_state'=>$order_state));

	}



	/**
	 * 订单修改后续处理
	 * @param $old
	 * @param $new
	 * @return unknown_type
	 */
	function _process_order($old,$new){
		if ($old['order_state'] == 1){
			if ($new['order_state'] == 2){
				self::_update_member($new['uid']);
				self::_update_member_discount($new['order_id']);
			}
		}
	}

	/**
	 * 更新用户数据
	 * @param $uid
	 * @return unknown_type
	 */
	function _update_member($uid){
        $this->load->model('Mmember');
        $flag = $this->Mmember->check_user_exist($uid);
        if ($flag){
            $user = $this->Mmember->get_user_info('username',$uid);
            $user['order_count']++;
            if (substr($uid,0,2) == 'CM'){
                if(!($user['order_count']%10)){
                    $user['discount'] += 0.1;
                }
                if(!($user['order_count']%100)){
                    $user['discount'] = round($user['discount']);
                    $user['lvl']++;
                }
                $max = $this->config->item('member_dis_max');
                if($user['discount'] >= $max){
                    $user['discount'] = $max;
                }
            }
            if($this->Mmember->update_member_data($user['uid'],array('order_count'=>$user['order_count'],'lvl'=>$user['lvl'],'discount'=>$user['discount']))){
                log_common('admin','admin_order.php','_update_member','update member succ',$user);
                return true;
            } else {
                log_common('admin','admin_order.php','_update_member','update member succ',$user);
                return false;
            }
        } else {
        	log_common('admin','admin_order.php','_update_member','user not exist',array('username'=>$uid));
            return false;
        }
	}

	function _update_member_discount($order_id){
		$this->load->helper('common');
		$info = get_order_info($order_id);
		$username = $info['uid'];
		$price = $info['price'];
		$this->load->model('Mmember');
		$flag = $this->Mmember->check_user_exist($username);
		if ($flag){
			$user_info = $this->Mmember->get_user_info('username',$username);
			$disc_type = $user_info['disc_type'];
			/*
			if ($disc_type == 1){
				$discount = $user_info['discount'];
			} elseif ($disc_type == 2){
				$discount = $real_price * ($user_info['discount']/100);
			} else {
				$discount = 0;
			}
			*/
			$this->load->model('Mconfigs');
			$banus = $this->Mconfigs->get_banus_config($user_info['utype']);
            $this->load->helper('common');
            $discount = get_discount($username,$order_id);
			$banus = $price * ($banus/100);
			$add_time = date('Y-m-d H:i:s');
			$values = array('username'=>$username,'order_id'=>$order_id,'price'=>$price,'discount'=>$discount,'banus'=>$banus,'add_time'=>$add_time);
			log_common('admin','admin_order.php','_update_member_discount','values',$values);
			return $this->Mmember->insert_new_discount($values);
		} else {
			log_common('admin','admin_order.php','_update_member_discount','username:'.$username.' not exists');
			return;
		}
	}

    function _get_order_info($order_id) {
        $this->load->model('Morders');
        $info = $this->Morders->get_order_info($order_id);
        $this->load->model('Mproduct');
        $p_info = $this->Mproduct->get_product_info($info['product']);
        if(!empty($p_info)){
            $info['p_name'] = $p_info['p_name'];
            $info['p_days'] = $p_info['p_days'];
            $info['week_num'] = $p_info['week_num'];
            $info['week_money'] = $p_info['week_money'];
        } else {
            $info['p_name'] = '';
            $info['p_days'] = '';
            $info['week_num'] = 0;
            $info['week_money'] = 0;
        }
        $this->load->helper('common');
        $info['order_discount'] = get_discount($info['uid'],$order_id);
        $this->config->load('setup');
        $states = $this->config->item('guest_state');
        $info['state_desc'] = $states[$info['order_state']];
        $this->load->model('Mgames');
        $info['game_name']      = $this->Mgames->get_game_name($info['game_id']);
        $info['area_name']      = $this->Mgames->get_area_name($info['game_area']);
        $info['server_name']    = $this->Mgames->get_server_name($info['game_server']);
        $info['group_name']     = $this->Mgames->get_group_info('en_name',$info['role_group'],'cn_name');
        $info['career_name']    = $this->Mgames->get_career_info('en_name',$info['role_career'],'cn_name');
        return $info;
    }

}

?>